package com.neusoft.hifly.mybatis.parsers;

import java.util.Collection;
import java.util.Map;

import org.apache.ibatis.reflection.MetaObject;

import com.baomidou.mybatisplus.core.parser.ISqlParser;
import com.baomidou.mybatisplus.core.parser.SqlInfo;
import com.baomidou.mybatisplus.core.toolkit.Assert;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.TableNameParser;
import com.baomidou.mybatisplus.extension.parsers.ITableNameHandler;

import com.neusoft.hifly.core.utils.GlobalConstants;

/**
 * 动态表名 SQL 解析器
 */
public class MyDynamicTableNameParser implements ISqlParser {
	private Map<String, ITableNameHandler> tableNameHandlerMap;

	@Override
	public SqlInfo parser(final MetaObject metaObject, final String sql) {
		Assert.isFalse(CollectionUtils.isEmpty(this.tableNameHandlerMap), "tableNameHandlerMap is empty.",
				new Object[0]);
		if (allowProcess(metaObject)) {
			final Collection<String> tables = new TableNameParser(sql).tables();
			if (CollectionUtils.isNotEmpty(tables)) {
				boolean sqlParsed = false;
				String parsedSql = sql;
				for (final String table : tables) {
					final ITableNameHandler tableNameHandler = this.tableNameHandlerMap
							.get(GlobalConstants.DYNAMIC_TABLE_NAME_PREFIX);
					if (null != tableNameHandler) {
						parsedSql = tableNameHandler.process(metaObject, parsedSql, table);
						sqlParsed = true;
					}
				}
				if (sqlParsed) {
					return SqlInfo.newInstance().setSql(parsedSql);
				}
			}
		}
		return null;
	}

	public boolean allowProcess(final MetaObject metaObject) {
		return true;
	}

	public Map<String, ITableNameHandler> getTableNameHandlerMap() {
		return tableNameHandlerMap;
	}

	public void setTableNameHandlerMap(final Map<String, ITableNameHandler> tableNameHandlerMap) {
		this.tableNameHandlerMap = tableNameHandlerMap;
	}

}